#!/usr/bin/env python3
"""OpenCloudOS LLM 部署工具的主入口点"""
import sys
import subprocess

from .utils.display import display
from .hardware.scanner import HardwareScanner
from .optimizer import Optimizer
from .models import ModelManager
from .runner import Runner
from .config import ConfigLoader


def main():
    """
    功能：主执行函数，协调整个部署流程
    :return: 无
    """
    display("🚀🚀🚀🚀 启动 OpenCloudOS LLM 部署工具...")

    try:
        config = ConfigLoader().load()

        display("🔍🔍🔍🔍🔍🔍🔍🔍 正在检测硬件配置...")
        scanner = HardwareScanner()
        hardware = scanner.scan()
        display("🖥🖥🖥 🖥🖥🖥🖥🖥🖥️" f"硬件检测结果:\n{format_hardware_info(hardware)}")

        optimizer = Optimizer(config)
        params = optimizer.optimize_params(hardware)
        display(f"⚙⚙⚙⚙⚙⚙⚙⚙️ 优化配置:\n{format_params(params)}")

        model_manager = ModelManager(config)
        model_tag = params["model"]
        model_manager.ensure_model(model_tag)

        runner = Runner(config)
        runner.run(model_tag, params)

    except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as e:
        display(f"❌❌❌❌❌❌❌❌ 发生错误: {e}")
        sys.exit(1)
    except KeyboardInterrupt:
        display("\n🛑🛑🛑 用户中断操作")
        sys.exit(1)


def format_hardware_info(hardware):
    """
    功能：格式化硬件信息用于显示
    :param hardware: 包含硬件信息的字典
    :return: 格式化后的硬件信息字符串
    """
    cpu_info = (
        f"• CPU: {hardware['cpu'].get('brand', '未知')}\n"
        f"  核心数: {hardware['cpu'].get('cores', 1)}核"
        f" {hardware['cpu'].get('threads', 2)}线程\n"
        f"  基准频率: {hardware['cpu'].get('base_freq', 0)}GHz\n"
        f"  综合评分: {hardware['cpu'].get('score', 1)}"
    )

    gpu_info = ""
    if hardware["gpu"]:
        gpu_info = (
            f"• GPU: {hardware['gpu']['name']}\n"
            f"  VRAM: {hardware['gpu']['vram']}GB\n"
            f"  CUDA核心: {hardware['gpu'].get('cuda_cores', 0)}"
        )
    else:
        gpu_info = "• GPU: 未检测到"

    disk_info = (
        f"• 磁盘: 总空间 {hardware['disk']['total_gb']}GB, "
        f"可用空间 {hardware['disk']['free_gb']}GB"
    )

    memory_info = f"• 内存: {hardware['memory']}GB"

    return f"{cpu_info}\n{memory_info}\n{gpu_info}\n{disk_info}"


def format_params(params):
    """
    功能：格式化优化参数用于显示
    :param params: 包含优化参数的字典
    :return: 格式化后的参数信息字符串
    """
    return (
        f"• 推荐模型: {params['model']}\n"
        f"• 上下文窗口: {params['ctx_size']} tokens\n"
        f"• CPU线程: {params['threads']}\n"
        f"• GPU加速层: {params.get('gpu_layers', 0)}"
    )


if __name__ == "__main__":
    main()
